/**
 * 阅读记录相关API接口
 * 基于后端API文档：我的模块API.md
 */

import type {
  ClearReadingRecordsResponse,
  DeleteReadingRecordResponse,
  GetReadingHistoryParams,
  GetReadingHistoryResponse,
  GetReadingStatsResponse,
  GetReadingStatusResponse,
  ReadingHistoryRespVO,
  ReadingRecord,
  ReadingStatsRespVO,
  TodayReadingRespVO,
} from '@/types/reading-records'
import { http } from '@/utils/request'

/**
 * 获取阅读记录列表
 * GET /api/reading-records/history
 */
export function getReadingHistory(params: GetReadingHistoryParams) {
  return http.get<GetReadingHistoryResponse>('/reading/reading-records/history', params)
}

/**
 * 获取阅读统计数据
 * GET /reading/reading-records/stats
 */
export function getReadingStats() {
  return http.get<GetReadingStatsResponse>('/reading/reading-records/stats')
}

/**
 * 获取今日阅读状态
 * GET /api/reading-status/today
 */
export function getTodayReadingStatus() {
  return http.get<GetReadingStatusResponse>('/reading/reading-status/today')
}

/**
 * 删除单条阅读记录
 * DELETE /api/reading-records/{recordId}
 */
export function deleteReadingRecord(recordId: number) {
  return http.delete<DeleteReadingRecordResponse>(`/reading/reading-records/${recordId}`)
}

/**
 * 清空所有阅读记录
 * DELETE /api/reading-records/clear
 */
export function clearAllReadingRecords() {
  return http.delete<ClearReadingRecordsResponse>('/reading/reading-records/clear')
}

/**
 * 获取今日阅读记录
 * GET /api/reading-records/today
 */
export function getTodayReadingRecords() {
  return http.get<{ code: number, message: string, data: TodayReadingRespVO }>('/reading/reading-records/today')
}

/**
 * 获取绘本阅读记录
 * GET /api/reading-records/book/{bookId}
 */
export function getBookReadingRecord(bookId: number) {
  return http.get<{ code: number, message: string, data: ReadingRecord }>(`/reading/reading-records/book/${bookId}`)
}

// ==================== 工具函数 ====================

/**
 * 格式化阅读时间
 */
export function formatReadingTime(seconds: number, options?: {
  unit?: 'second' | 'minute' | 'hour'
  showUnit?: boolean
  precision?: number
}): string {
  const { unit = 'minute', showUnit = true, precision = 1 } = options || {}

  if (seconds < 60 && unit !== 'second') {
    return showUnit ? `${seconds}秒` : String(seconds)
  }

  switch (unit) {
    case 'second':
      return showUnit ? `${seconds}秒` : String(seconds)
    case 'minute':
      const minutes = (seconds / 60).toFixed(precision)
      return showUnit ? `${minutes}分钟` : minutes
    case 'hour':
      const hours = (seconds / 3600).toFixed(precision)
      return showUnit ? `${hours}小时` : hours
    default:
      return showUnit ? `${seconds}秒` : String(seconds)
  }
}

/**
 * 格式化阅读进度
 */
export function formatReadingProgress(progress: number): string {
  return `${Math.round(progress)}%`
}

/**
 * 获取阅读进度颜色
 */
export function getProgressColor(progress: number): string {
  if (progress >= 100)
    return '#4caf50' // 完成 - 绿色
  if (progress >= 70)
    return '#66bb6a' // 高进度 - 浅绿
  if (progress >= 30)
    return '#ffa726' // 中等进度 - 橙色
  return '#ff6b6b' // 低进度 - 红色
}

/**
 * 获取阅读状态文本
 */
export function getReadingStatusText(record: ReadingHistoryRespVO): string {
  if (record.isCompleted) {
    return '已完成'
  }
  if (record.readingProgress > 0) {
    return `进行中 ${formatReadingProgress(record.readingProgress)}`
  }
  return '未开始'
}

/**
 * 格式化阅读日期
 */
export function formatReadingDate(dateStr: string, options?: {
  showTime?: boolean
  relative?: boolean
}): string {
  const { showTime = false, relative = true } = options || {}

  const date = new Date(dateStr)
  const now = new Date()
  const diffMs = now.getTime() - date.getTime()
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))

  if (relative) {
    if (diffDays === 0) {
      return showTime ? `今天 ${formatTime(date)}` : '今天'
    }
    else if (diffDays === 1) {
      return showTime ? `昨天 ${formatTime(date)}` : '昨天'
    }
    else if (diffDays < 7) {
      return showTime ? `${diffDays}天前 ${formatTime(date)}` : `${diffDays}天前`
    }
  }

  // 非相对时间格式
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')

  let result = `${year}-${month}-${day}`

  if (showTime) {
    result += ` ${formatTime(date)}`
  }

  return result
}

/**
 * 格式化时间
 */
function formatTime(date: Date): string {
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${hours}:${minutes}`
}

/**
 * 计算阅读效率
 */
export function calculateReadingEfficiency(record: ReadingHistoryRespVO): {
  efficiency: number
  level: 'low' | 'medium' | 'high'
  text: string
} {
  if (!record.readingTime || record.readingTime === 0) {
    return { efficiency: 0, level: 'low', text: '暂无数据' }
  }

  // 假设平均每分钟阅读进度为1%
  const expectedProgress = record.readingTime / 60
  const efficiency = (record.readingProgress / expectedProgress) * 100

  let level: 'low' | 'medium' | 'high' = 'low'
  let text = '较慢'

  if (efficiency >= 120) {
    level = 'high'
    text = '很快'
  }
  else if (efficiency >= 80) {
    level = 'medium'
    text = '正常'
  }

  return { efficiency: Math.round(efficiency), level, text }
}

/**
 * 处理阅读记录封面URL
 */
export function processBookCover(coverUrl: string): string {
  if (!coverUrl) {
    // 返回空字符串，让组件使用图标占位符
    return ''
  }

  // 如果是相对路径，添加基础URL
  if (!coverUrl.startsWith('http')) {
    const baseUrl = import.meta.env.VITE_API_BASE_URL || ''
    return `${baseUrl}${coverUrl}`
  }

  return coverUrl
}

/**
 * 生成阅读记录的唯一键
 */
export function getRecordKey(record: ReadingHistoryRespVO): string {
  return `${record.bookId}_${record.id}`
}

/**
 * 过滤阅读记录
 */
export function filterReadingRecords(
  records: ReadingHistoryRespVO[],
  filters: {
    keyword?: string
    completed?: boolean
    dateRange?: [string, string]
    minProgress?: number
  },
): ReadingHistoryRespVO[] {
  let filtered = [...records]

  // 关键词过滤
  if (filters.keyword) {
    const keyword = filters.keyword.toLowerCase()
    filtered = filtered.filter(record =>
      record.bookTitle.toLowerCase().includes(keyword),
    )
  }

  // 完成状态过滤
  if (filters.completed !== undefined) {
    filtered = filtered.filter(record => record.isCompleted === filters.completed)
  }

  // 日期范围过滤
  if (filters.dateRange) {
    const [startDate, endDate] = filters.dateRange
    filtered = filtered.filter((record) => {
      const recordDate = new Date(record.lastReadAt).getTime()
      const start = new Date(startDate).getTime()
      const end = new Date(endDate).getTime()
      return recordDate >= start && recordDate <= end
    })
  }

  // 最小进度过滤
  if (filters.minProgress !== undefined) {
    filtered = filtered.filter(record => record.readingProgress >= filters.minProgress)
  }

  return filtered
}

/**
 * 排序阅读记录
 */
export function sortReadingRecords(
  records: ReadingHistoryRespVO[],
  sortType: 'time_desc' | 'time_asc' | 'progress_desc' | 'progress_asc' | 'title_asc',
): ReadingHistoryRespVO[] {
  const sorted = [...records]

  switch (sortType) {
    case 'time_desc':
      return sorted.sort((a, b) => new Date(b.lastReadAt).getTime() - new Date(a.lastReadAt).getTime())
    case 'time_asc':
      return sorted.sort((a, b) => new Date(a.lastReadAt).getTime() - new Date(b.lastReadAt).getTime())
    case 'progress_desc':
      return sorted.sort((a, b) => b.readingProgress - a.readingProgress)
    case 'progress_asc':
      return sorted.sort((a, b) => a.readingProgress - b.readingProgress)
    case 'title_asc':
      return sorted.sort((a, b) => a.bookTitle.localeCompare(b.bookTitle))
    default:
      return sorted
  }
}

// ==================== 错误处理 ====================

/**
 * 处理阅读记录API错误
 */
export function handleReadingRecordsError(error: any): string {
  const errorMessages: Record<number, string> = {
    50006: '阅读记录不存在',
  }

  const code = error?.response?.data?.code || error?.code
  return errorMessages[code] || error?.message || '操作失败，请重试'
}

// ==================== 缓存相关 ====================

/**
 * 缓存键名
 */
export const CACHE_KEYS = {
  READING_STATS: 'reading_stats',
  TODAY_STATUS: 'today_reading_status',
  READING_HISTORY: 'reading_history',
}

/**
 * 清除阅读记录相关缓存
 */
export function clearReadingRecordsCache() {
  Object.values(CACHE_KEYS).forEach((key) => {
    uni.removeStorageSync(key)
  })
}

/**
 * 缓存阅读统计
 */
export function cacheReadingStats(stats: ReadingStatsRespVO) {
  uni.setStorageSync(CACHE_KEYS.READING_STATS, stats)
}

/**
 * 获取缓存的阅读统计
 */
export function getCachedReadingStats(): ReadingStatsRespVO | null {
  try {
    return uni.getStorageSync(CACHE_KEYS.READING_STATS) || null
  }
  catch {
    return null
  }
}
